import serial
import time
from queue import Queue
import select


import logging

logging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s')

logger = logging.getLogger(__name__)

import json
import asyncio
from db_method import DbMethod
from command_parse import CommandParse
from serial_connect import SerialPortMethod
import traceback

from wave_mesh import WaveMesh

class Ble:

    def __init__(self):
        self.ser = serial.Serial('/dev/ttyS5', 9600)

    def start_ble_server(self):

        while True:
            try:
                if self.ser.in_waiting > 0:
                    time.sleep(0.5)
                    data = self.ser.read(self.ser.in_waiting).decode().upper()
                    logger.info(f"receive_str:{data}")
                    self.processing_tasks(data=data)
            except Exception as e:
                trace = traceback.format_exc()
                logger.error(f"Exception occurred at line: {trace.splitlines()[-2]}")
                logger.error(str(e))

            select.select([self.ser], [], [], 0.1)

    def ble_send(self, data: str):
        '''蓝牙发送数据'''

        logger.info(f"蓝牙发送数据：{data}")

        self.ser.write(data.encode())

    def parse_send_command(self, data):

        '''data: str
        crc 是不正确的
        E50E00000000000300000000EF00  获取传感器所有的值
        E5 0E 0000 10 0000 06 00000010 2211  采集周期
        E5 0E 0000 0c 0000 06 00000001 2211  上传周期
        '''

        pass

    def processing_tasks(self, data: str): # 任务处理

        # parse_result = CommandParse(data).parse_result

        if data == "E50E00000000000300000000EF00": # 获取所有传感器的值

            with DbMethod() as dm:

                sensor_info = dm.get_all_sensor_info_by_now()

            self.ble_send(json.dumps([i["row_command"] for i in sensor_info]))

        elif data.startswith("E50E00000C"): # 上传周期
             
            cyc_flage = int(data[-5])

            WaveMesh().change_up_time(cyc_flage)

            self.ble_send("ok")

        elif data.startswith("E50E000010") : # 采集周期

            with SerialPortMethod() as spm:

                spm.send_data(data)

            self.ble_send("ok")

        # E5 0E 0000 12 0001 06 00000001 63C4

        elif data.startswith("E50E000012"): # 灯灯

            with SerialPortMethod() as spm:

                spm.send_data(data)

            self.ble_send("ok")

        else:

            self.ble_send("请确认上发命令是否正确！")







# 创建 Ble 实例并执行协程
ble = Ble()
ble.start_ble_server()